package com.yuke.cloud.service.omc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yuke.cloud.common.base.constant.GlobalConstant;
import com.yuke.cloud.common.base.constant.MQConstants;
import com.yuke.cloud.common.base.dto.MsgNotificationBody;
import com.yuke.cloud.common.base.enums.ErrorCodeEnum;
import com.yuke.cloud.common.core.mq.RabbitMetaMessage;
import com.yuke.cloud.common.core.support.BaseService;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.cmc.dto.CmsSysInfoDto;
import com.yuke.cloud.service.api.cmc.service.CmcFeignApi;
import com.yuke.cloud.service.api.omc.exceptions.OmcBizException;
import com.yuke.cloud.service.api.opc.service.OpcSendNotifyFeignApi;
import com.yuke.cloud.service.api.smc.dto.ShopInfoDto;
import com.yuke.cloud.service.api.smc.service.SmcFeignApi;
import com.yuke.cloud.service.api.wmc.service.WmcStorageFeignApi;
import com.yuke.cloud.service.omc.controller.frontend.OdsBillPayController;
import com.yuke.cloud.service.omc.controller.frontend.PayController;
import com.yuke.cloud.service.omc.dao.OdsCommissionMapper;
import com.yuke.cloud.service.omc.dto.CommissionInfo;
import com.yuke.cloud.service.omc.dto.OdsCommissionDto;
import com.yuke.cloud.service.omc.entity.OdsBill;
import com.yuke.cloud.service.omc.entity.OdsCommission;
import com.yuke.cloud.service.omc.entity.OdsCommissionOrder;
import com.yuke.cloud.service.omc.entity.OdsOrder;
import com.yuke.cloud.service.omc.service.OdsBillService;
import com.yuke.cloud.service.omc.service.OdsCommissionOrderService;
import com.yuke.cloud.service.omc.service.OdsCommissionService;
import com.yuke.cloud.service.omc.service.OdsOrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;


/**
 * Created by wg on 2019/05/18.
 */
@Service
@Transactional
public class OdsCommissionServiceImpl extends BaseService<OdsCommission> implements OdsCommissionService {
    @Resource
    private OdsCommissionMapper odsCommissionMapper;

    @Resource
    private OdsOrderService odsOrderService;
    @Resource
    private OdsCommissionOrderService odsCommissionOrderService;

    @Value("${yuke.shop-commission-rate}")
    private Double shopCommissionRate;

    @Resource
    private SmcFeignApi smcFeignApi;

    @Resource
    private CmcFeignApi cmcFeignApi;
    @Resource
    private OpcSendNotifyFeignApi opcSendNotifyFeignApi;

    @Autowired
    private OdsBillService odsBillService;
    @Autowired
    private OdsBillPayController odsBillPayController;
    @Autowired
    private PayController payController;
    @Resource
    private WmcStorageFeignApi wmcStorageFeignApi;

    @Override
    public int saveCommission(OdsCommission odsCommission) {
        // 从订单表中获取该店面对应的佣金订单
        List<OdsOrder> odsOrders = odsOrderService.getCommissionOrders(odsCommission.getShopId());
        if (odsOrders == null || odsOrders.size() <= 0) {
            return -1;
        }
        //获取C端佣金返现率
        Long shopId = odsCommission.getShopId();
        Long groupId = 220839532667469824L;
        Wrapper wrap = wmcStorageFeignApi.getGroupIdByShopId(shopId);
        if (wrap.getCode() == 200 && wrap.getResult() != null ){
            groupId = Long.valueOf(wrap.getResult().toString());
        }

        CmsSysInfoDto cmsSysInfoDto  = cmcFeignApi.getSysInfoDtoByType(groupId,GlobalConstant.SysInfo.SYS_INFO_ORDER_REBATE);
        if (cmsSysInfoDto != null && cmsSysInfoDto.getInfoValue() != null) {
            shopCommissionRate = Double.parseDouble(cmsSysInfoDto.getInfoValue());
        }

        Long commissionId = super.generateId();

        Integer amount = 0;
        for (OdsOrder odsOrder : odsOrders) {
            amount += (odsOrder.getAmountPaid() - odsOrder.getFreightPayable() - odsOrder.getRefundMoney()); // 扣除运费及已退款的部分

            OdsCommissionOrder odsCommissionOrder = new OdsCommissionOrder();
            odsCommissionOrder.setCommissionOrderId(super.generateId());
            odsCommissionOrder.setCommissionId(commissionId);
            odsCommissionOrder.setOrderId(odsOrder.getOrderId());
            odsCommissionOrderService.save(odsCommissionOrder);

            // 修改订单表中的commission_status
            OdsOrder odsOrderTemp = new OdsOrder();
            odsOrderTemp.setOrderId(odsOrder.getOrderId());
            odsOrderTemp.setCommissionStatus((byte)1); // 申请审核中

            odsOrderService.update(odsOrderTemp);
        }

        odsCommission.setCommissionId(commissionId);
        odsCommission.setCheckStatus((byte)1); // 审核中
        odsCommission.setCreateTime(new Date());
        odsCommission.setAmount((int)Math.round(amount * shopCommissionRate));

        super.save(odsCommission);
//        odsCommissionMapper. insert(odsCommission);

        // 提现审核通知管理员处理
        Map map = new HashMap();
        map.put("MessageType", "findWarehouseAdmin");
        map.put("shopIds", odsCommission.getShopId().toString());
        map.put("body", "通知订单管理员，有提现申请需要审核");
        RabbitMetaMessage rabbitMetaMessage = new RabbitMetaMessage();
        rabbitMetaMessage.setExchange(MQConstants.BUSINESS_EXCHANGE);
        rabbitMetaMessage.setRoutingKey(MQConstants.BUSINESS_KEY_WMC);
        rabbitMetaMessage.setPayload(JSON.toJSONString(map));

        return 0;
    }

    @Override
    public void updateCommission(OdsCommission odsCommission) {
        String jsonString = JSONObject.toJSONString(odsCommission);
        System.out.println("修改订单表"+jsonString);
        odsCommission.setRebackType((byte)1);
        if( odsCommission.getRebackType() == null ){

            // 修改订单表中的commission_status
            Example example = new Example(OdsCommissionOrder.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("commissionId", odsCommission.getCommissionId());
            List<OdsCommissionOrder> odsCommissionOrders = odsCommissionOrderService.selectByExample(example);

            if (odsCommissionOrders == null || odsCommissionOrders.size() <= 0) {
                throw new OmcBizException(ErrorCodeEnum.GL99990100);
            }

            for (OdsCommissionOrder odsCommissionOrder : odsCommissionOrders) {
                // 修改订单表中的commission_status
                OdsOrder odsOrderTemp = new OdsOrder();
                odsOrderTemp.setOrderId(odsCommissionOrder.getOrderId());
                odsOrderTemp.setCommissionStatus(odsCommission.getCheckStatus()); // 审核状态

                odsOrderService.update(odsOrderTemp);
            }
        }
            super.update(odsCommission);

        // 审核结果通知用户
        List<ShopInfoDto> shopInfoDtos = smcFeignApi.getShopUserIdByShopIds(Arrays.asList(odsCommission.getShopId()));

        if (shopInfoDtos != null && shopInfoDtos.size() > 0) {
            Long userId = shopInfoDtos.get(0).getUserId();

            MsgNotificationBody msg = new MsgNotificationBody();
            msg.setMsgType("shopMsg");
            msg.setTitle("审核结果通知");
            if (odsCommission.getCheckStatus() == 0) { // 拒绝
                msg.setContent("您收益提现申请审核未通过，请联系客服！");
            } else if (odsCommission.getCheckStatus() == 2) { // 通过审核
                msg.setContent("您收益提现申请审核已通过，请进行提现操作！");
            }

            msg.setTime(new Date());
            msg.setReceiveType((byte) 3);
            msg.setMsgType("orderMsg");
            opcSendNotifyFeignApi.sendnotify(userId.toString(), msg.getTitle(), msg.getContent(), 0);
            opcSendNotifyFeignApi.sendnotify(userId.toString(), msg.getTitle(), JSON.toJSONString(msg), 1);
        }
    }

    /**
     * 返回0：正常，-1，没有对应的提现单
     * @param odsCommission
     * @return
     */
    @Override
    public int withdrawCommission(OdsCommission odsCommission) {

        if(odsCommission.getRebackType() == null){
            return -1;
        }
        // 先判断是否有提现单
        OdsCommission commission = this.findById(odsCommission.getCommissionId());
        if (commission == null || commission.getCheckStatus() != 2) {
            return -1;
        }
        System.out.println(commission);
        System.out.println(commission.getShopId());
        // 返钱操作
        List<ShopInfoDto> shopInfoDtos = smcFeignApi.getShopInfoByShopIds(Arrays.asList(commission.getShopId()));
        if (shopInfoDtos == null || shopInfoDtos.size() <= 0) {
            throw new OmcBizException(ErrorCodeEnum.GL99990002);
        }

        Long userId = shopInfoDtos.get(0).getUserId();
        Byte billtype = 0;
        String msgText = "";
        Long uid = 0L;
        if(odsCommission.getRebackType().equals((byte)0)){

            msgText = "您的佣金收益";
            // 修改提现单及订单状态
            Example example = new Example(OdsCommissionOrder.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("commissionId", commission.getCommissionId());
            List<OdsCommissionOrder> odsCommissionOrders = odsCommissionOrderService.selectByExample(example);
            //平台佣金处理
            if (odsCommissionOrders != null && odsCommissionOrders.size() > 0) {
                for (OdsCommissionOrder odsCommissionOrder : odsCommissionOrders) {
                    // 修改订单表中的commission_status
                    OdsOrder odsOrderTemp = new OdsOrder();
                    odsOrderTemp.setOrderId(odsCommissionOrder.getOrderId());
                    odsOrderTemp.setCommissionStatus((byte)3); // 已发放
                    odsOrderService.update(odsOrderTemp);
                }
            } else {
                throw new OmcBizException(ErrorCodeEnum.GL99990100);
            }
//            if (payController.transferCommission(shopInfoDtos.get(0).getAccountNo(), commission.getAmount()) != 0) {
//               throw new OmcBizException(ErrorCodeEnum.GL99990500);
//             }
        }if(odsCommission.getRebackType().equals((byte)2)){
            msgText = "您的发展客户提成收益";
            // 修改提现单及订单状态
            Example example = new Example(OdsCommissionOrder.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("commissionId", commission.getCommissionId());
            List<OdsCommissionOrder> odsCommissionOrders = odsCommissionOrderService.selectByExample(example);
            //提成处理
            if (odsCommissionOrders != null && odsCommissionOrders.size() > 0) {
                for (OdsCommissionOrder odsCommissionOrder : odsCommissionOrders) {
                    // 修改订单表中的commission_status
                    OdsOrder odsOrderTemp = new OdsOrder();
                    odsOrderTemp.setOrderId(odsCommissionOrder.getOrderId());
                    odsOrderTemp.setShopCommissionAmount(odsCommission.getAmount());
                    odsOrderService.update(odsOrderTemp);
                }
            } else {
                throw new OmcBizException(ErrorCodeEnum.GL99990100);
            }
            if (payController.transferCommission(shopInfoDtos.get(0).getAccountNo(), commission.getAmount()) != 0) {
               throw new OmcBizException(ErrorCodeEnum.GL99990500);
             }
            OdsCommission odsCommissionTemp = new OdsCommission();
            odsCommissionTemp.setCommissionId(commission.getCommissionId());
            odsCommissionTemp.setCheckStatus((byte)3); // 已发放
            super.update(odsCommissionTemp);
        }else {

            billtype = 4;
            msgText = "您的平台满减返现收益";
            //todo 20191214 平台不返现，改成到C 端账户充值

            //获取最新的一条记录，拿账户余额balance值
            OdsBill bill=odsBillService.selectLastOneByUserId(userId);
            OdsBill odsBill = new OdsBill();
            odsBill.setBillId(super.generateId());
            if (bill == null || bill.getBalance() == null){
                odsBill.setBalance(0);
            }else{
                odsBill.setBalance(bill.getBalance());
            }
            odsBill.setBillType(billtype);
            odsBill.setUserId(shopInfoDtos.get(0).getUserId());
            odsBill.setBalanceType((byte)1);
            odsBill.setAmount(commission.getAmount());
            odsBill.setSerialNum(commission.getCommissionId().toString());
            uid = odsBillPayController.doBillUpdate(odsBill);

            OdsCommission odsCommissionTemp = new OdsCommission();
            odsCommissionTemp.setCommissionId(commission.getCommissionId());
            odsCommissionTemp.setCheckStatus((byte)3); // 已发放
            super.update(odsCommissionTemp);

        }



        // 转账结果通知用户
        if (shopInfoDtos != null && shopInfoDtos.size() > 0 && uid > 0) {

            double amount = new BigDecimal(((double) commission.getAmount()) / 100).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
            MsgNotificationBody msg = new MsgNotificationBody();

            msg.setTitle("个人账户变动通知");
            msg.setContent(msgText + String.valueOf(amount) + "元，已成功加入个人账户！");

            msg.setTime(new Date());
            msg.setReceiveType((byte) 3);
            msg.setMsgType("orderMsg");
            opcSendNotifyFeignApi.sendnotify(userId.toString(), msg.getTitle(), msg.getContent(), 0);
            opcSendNotifyFeignApi.sendnotify(userId.toString(), msg.getTitle(), JSON.toJSONString(msg), 1);
        }else{
            return -1;
        }

        return 0;
    }

    /**
     * 获取云顶商人或云顶店铺累计收益及可提取的收益
     */
    public CommissionInfo getCommissionInfo(Long shopId) {
        // 获取已提现的金额， check_status=3
        Integer total = odsCommissionMapper.getTotalCommission(shopId, (byte)3);

        // 从订单表中获取该店面对应的可提现金额
        Integer balance = 0;
        List<OdsOrder> odsOrders = odsOrderService.getCommissionOrders(shopId);
        if (odsOrders != null && odsOrders.size() > 0) {
            Integer amount = 0;
            for (OdsOrder odsOrder : odsOrders) {
                amount += (odsOrder.getAmountPaid() - odsOrder.getFreightPayable() - odsOrder.getRefundMoney()); // 扣除运费及已退款的部分
            }

            balance = (int)Math.round(amount * shopCommissionRate);
        }

        CommissionInfo commissionInfo = new CommissionInfo();
        commissionInfo.setShopId(shopId);
        commissionInfo.setTotal(total);
        commissionInfo.setBalance(balance);

        return commissionInfo;
    }

    @Override
    public int saveCommissionMonthRebate(OdsCommission odsCommission) {
        Long commissionId = super.generateId();
        odsCommission.setCommissionId(commissionId);
        odsCommission.setCheckStatus((byte)1); // 审核中
        odsCommission.setCreateTime(new Date());
        odsCommission.setUpdateTime(new Date());
        super.save(odsCommission);

        // 提现审核通知管理员处理
        Map map = new HashMap();
        map.put("MessageType", "findWarehouseAdmin");
        map.put("shopIds", odsCommission.getShopId().toString());
        map.put("body", "通知订单管理员，有月度满减申请需要审核");
        RabbitMetaMessage rabbitMetaMessage = new RabbitMetaMessage();
        rabbitMetaMessage.setExchange(MQConstants.BUSINESS_EXCHANGE);
        rabbitMetaMessage.setRoutingKey(MQConstants.BUSINESS_KEY_WMC);
        rabbitMetaMessage.setPayload(JSON.toJSONString(map));

        return 0;
    }

    @Override
    @Transactional
    public int saveShopCommission(OdsCommissionDto odsCommissionDto) {
        OdsCommission odsCommission = new OdsCommission();
        BeanUtils.copyProperties(odsCommissionDto,odsCommission);
        Long commissionId = super.generateId();
        odsCommission.setCommissionId(commissionId);
        odsCommission.setCheckStatus((byte)1); // 审核中
        odsCommission.setCreateTime(new Date());
        odsCommission.setUpdateTime(new Date());
        super.save(odsCommission);

        OdsCommissionOrder odsCommissionOrder = new OdsCommissionOrder();
        odsCommissionOrder.setCommissionOrderId(super.generateId());
        odsCommissionOrder.setOrderId(odsCommissionDto.getOrderId());
        odsCommissionOrder.setCommissionId(commissionId);
        odsCommissionOrderService.save(odsCommissionOrder);

        // 提现审核通知管理员处理
        Map map = new HashMap();
        map.put("MessageType", "findWarehouseAdmin");
        map.put("shopIds", odsCommissionDto.getShopId().toString());
        map.put("body", "通知订单管理员，有返利信息需要审核");
        RabbitMetaMessage rabbitMetaMessage = new RabbitMetaMessage();
        rabbitMetaMessage.setExchange(MQConstants.BUSINESS_EXCHANGE);
        rabbitMetaMessage.setRoutingKey(MQConstants.BUSINESS_KEY_WMC);
        rabbitMetaMessage.setPayload(JSON.toJSONString(map));

        return 0;
    }


    @Override
    public Map<String,String> getMonthRebate(Long groupId) {
         Map<String,String> map = cmcFeignApi.getMonthRebate(groupId);
         return map;

    }

    //店铺发展的会员消费后平台给店铺返利结算比率
    @Override
    public CmsSysInfoDto getShopCommissionRebate(Long groupId) {
        CmsSysInfoDto map = cmcFeignApi.getSysInfoDtoByType(groupId,GlobalConstant.SysInfo.SYS_INFO_ORDER_COMMISSION);
        return map;

    }
    @Override
    public List<ShopInfoDto> getShopIdsByCondition() {
        List<ShopInfoDto> list = smcFeignApi.getShopIdsByCondition();
        return list;

    }


}
